let timer = null
import { getMessageCode, updatePassword } from '../../../api/index'
import { hex_md5_salt } from '../../../utils/md5'

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    userInfo: {
      type: Object,
      value: {}
    }
  },
  data: {
    time: 0,
    pwd: '',
    code: ''
  },
  methods: {
    beforeOpen () {
      if (timer)clearInterval(timer)
      timer = null
      this.setData({ code: '', pwd: '', time: 0 })
    },
    codeTimer () {
      this.setData({ time: 60 })
      timer = setInterval(() => {
        this.data.time--
        this.setData({ time: this.data.time })
        if (this.data.time <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    },
    async sendCode () {
      try {
        let reg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/
        if (this.data.time > 0 && this.isSendCode) {
          return
        }
        if (!this.data.userInfo.userInfo.mobile || !reg.test(this.data.userInfo.userInfo.mobile)) {
          wx.showToast({ title: '请输入正确的手机号！', icon: 'none' })
          return
        }
        this.isSendCode = true
        await getMessageCode({ mobile: this.data.userInfo.userInfo.mobile })
        this.isSendCode = false
        await this.codeTimer()
        wx.showToast({ title: '短信验证码已发送', icon: 'none' })
      } catch (err) {
        this.isSendCode = false
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    changeInput ({ currentTarget: { dataset: { key } }, detail: { value } }) {
      this.setData({ [key]: value })
    },
    async confirm () {
      try {
        if (!this.data.code) {
          wx.showToast({ title: '请输入验证码！', icon: 'none' })
          return
        }
        if (!this.data.pwd) {
          wx.showToast({ title: '请输入新密码！', icon: 'none' })
          return
        }
        let query = {
          mobile: this.data.userInfo.userInfo.mobile,
          msgCode: this.data.code,
          password: hex_md5_salt(encodeURIComponent(this.data.pwd))
        }
        await updatePassword({ ...query })
        wx.showToast({ title: '修改成功！', icon: 'none' })
        this.triggerEvent('change')
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    close () {
      this.triggerEvent('close')
    }
  },
})